package com.util ;

import cn.hutool.core.util.HexUtil;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;

public class DESUtil {

    /**
     * 加密
     * @param datasource byte[]
     * @param password String
     * @return byte[]
     */
    //DES算法
    public static byte[] desCrypto(byte[] datasource, byte[] password) {
        try{
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password);
            //创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            //Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            //用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            //现在，获取数据并加密
            //正式执行加密操作
            return cipher.doFinal(datasource);
        }catch(Throwable e){
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        String source = "C86A3D8900000000";
        String key = "00000000000000000000000000000000";
        // 23129287BB4B0AE4
//        String encryptData1 = encrypt(source, key);
        String encryptData1 = HexUtil.encodeHexStr(desCrypto(HexUtil.decodeHex(source) , HexUtil.decodeHex(key))) ;
//        String dencryptData1 = decrypt(encryptData1,key);
//        System.out.println("解密后: " + dencryptData1);
    }
}
